package com.lanzuo.yxd.scanner.log;// ScanLogWebSocket.java


import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/ws/scan-logs")
@Component
public class ScanLogWebSocket {

    // 存储所有连接的 session
    private static final CopyOnWriteArraySet<Session> sessions = new CopyOnWriteArraySet<>();

    // 广播消息给所有客户端
    public static void broadcast(ScanLog scanLog) {
        String message = JSONUtil.toJsonPrettyStr(scanLog);
        for (Session session : sessions) {
            if (session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    System.err.println("WebSocket 发送失败: " + e.getMessage());
                    sessions.remove(session);
                }
            }
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        System.out.println("WebSocket 连接建立，当前连接数: " + sessions.size());
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        System.out.println("WebSocket 连接关闭，当前连接数: " + sessions.size());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.err.println("WebSocket 发生错误: " + error.getMessage());
        sessions.remove(session);
    }
}